//
//  ProfileEditViewController.m
//  XPhoto
//
//  Created by baboy on 2020/4/19.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "ProfileEditViewController.h"
#import <AFNetworking/UIButton+AFNetworking.h>
#import "MediaEditTableViewCell.h"
#import "AvatarTableViewCell.h"
#import "TextEditorViewController.h"
#import <BKKit/BKNavigationController.h>
#import "BKActionSheet.h"
#import "PhotoCameraViewController.h"
#import "PhotoLibViewController.h"
#import "SelectionViewController.h"
#import "SysDict.h"
#import "MobileBindViewController.h"

#define ACTION_SHEET_ITEM_TAG_AVATAR_PHOTO_LIB      0
#define ACTION_SHEET_ITEM_TAG_AVATAR_TAKE_PHOTO     1

@interface ProfileEditViewController ()<UITableViewDelegate, UITableViewDataSource, TextEditorDelegate, BKActionSheetDelegate,PhotoEditDelegate, SelectionDelegate, SelectionDelegate, MobileBindDelegate>
@property(nonatomic, strong) NSArray *editableFields;
@property(nonatomic, strong) PhotoAsset *avatarAsset;
@end

@implementation ProfileEditViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        self.editPropertySingly = YES;
        self.updatedUserInfo = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image.png"]
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(cancel:)];
    //批量编辑
    if (!self.editPropertySingly) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image.png"]
                                                                                 style:UIBarButtonItemStylePlain
                                                                                target:self
                                                                                action:@selector(finished:)];
    }
    self.user = [User currentUser];
    self.tableView.tableFooterView = [UIView new];
    self.editableFields = @[
        @{
            @"title":NSLocalizedString(@"avatar", @"标签"),
            @"propertyName":@"avatar"
        },
        @{
            @"title":NSLocalizedString(@"nickname", @"标签"),
            @"propertyName":@"nickname",
            @"editor":@"TextEditorViewController"
        },
        @{
            @"title":NSLocalizedString(@"gender", @"标签"),
            @"propertyName":@"gender",
            @"editor":@"SelectionViewController"
        },
        @{
            @"title":NSLocalizedString(@"userName", @"标签"),
            @"propertyName":@"userName",
            @"editor":@"TextEditorViewController"
        },
        @{
            @"title":NSLocalizedString(@"mobile", @"标签"),
            @"propertyName":@"mobile",
            @"editor":@"MobileBindViewController"
        },
        @{
            @"title":NSLocalizedString(@"intro", @"标签"),
            @"propertyName":@"intro",
            @"editor":@"TextEditorViewController"
        }
    ];
    [self.tableView reloadData];
}
- (void)cancel:(id)button{
    if (self.delegate && [self.delegate respondsToSelector:@selector(profileEditViewControllerShouldCancel:)]) {
        BOOL f = [self.delegate profileEditViewControllerShouldCancel:self];
        if (!f) {
            return;
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)finished:(id)button{
    if (self.delegate && [self.delegate respondsToSelector:@selector(profileEditViewControllerShouldFinished:)]) {
        BOOL f = [self.delegate profileEditViewControllerShouldFinished:self];
        if (!f) {
            return;
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 104;
    }
    return UITableViewAutomaticDimension;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.editableFields.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *field = [self.editableFields objectAtIndex:indexPath.row];
    NSString *propertyName = [field valueForKey:@"propertyName"];
    
    if ([propertyName isEqualToString:@"avatar"]) {
        AvatarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AvatarTableViewCell class])];
        if (!cell) {
            cell = loadViewFromNib([AvatarTableViewCell class], self);
            [cell.avatarButton addTarget:self action:@selector(changeAvatar:) forControlEvents:UIControlEventTouchUpInside];
        }
        if (self.user.avatarThumb) {
            [cell.avatarButton setImageForState:UIControlStateNormal withURL:self.avatarAsset ? [NSURL fileURLWithPath:self.avatarAsset.originPath]:[NSURL URLWithString:self.user.avatarThumb]];
        }
        return cell;
    }
    MediaEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MediaEditTableViewCell class])];
    if (!cell) {
        cell = loadViewFromNib([MediaEditTableViewCell class], self);
        cell.leftImageHidden = YES;
        cell.leftImageView.hidden = YES;
    }
    cell.titleLabel.text = [field valueForKey:@"title"];
    id val = [self.updatedUserInfo valueForKey:propertyName];
    if (!val) {
        val = [self.user valueForKey:propertyName];
    }
    
    if ([propertyName isEqualToString:@"gender"]) {
        SysDictItem *dictItem = [SysDict itemForValue:[val description] dictKey:SYS_DICT_GENDER_KEY];
        cell.detailLabel.text = dictItem.title;
        return cell;
    }
    cell.detailLabel.text = val;
    
    if ([propertyName isEqualToString:@"userName"] && self.user.userName) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    cell.accessoryType = [field valueForKey:@"editor"] ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *field = [self.editableFields objectAtIndex:indexPath.row];
    NSString *propertyName = [field valueForKey:@"propertyName"];
    NSString *editor = [field valueForKey:@"editor"];
    if (!editor) {
        return;
    }
    id vc = [[NSClassFromString(editor) alloc] init];
    if (!vc) {
        return;
    }
    if ([propertyName isEqualToString:@"userName"]) {
        if (self.user.userName) {
            return;
        }
    }
    if ([propertyName isEqualToString:@"gender"]) {
        SelectionViewController *svc = vc;
        svc.tag = indexPath.row;
        svc.delegate = self;
        svc.maxSelectionCount = 1;
        SysDict *dict = [SysDict dictForKey:SYS_DICT_GENDER_KEY];
        NSMutableArray *items = [NSMutableArray array];
        for (NSInteger i = 0, n = dict.items.count; i < n; i++) {
            SysDictItem *dictItem = [dict.items objectAtIndex:i];
            SelectionItem *item = [[SelectionItem alloc] initWithTitle:dictItem.title value:dictItem];
            [items addObject:item];
        }
        svc.items = items;
        BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:svc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
    
    if([vc isKindOfClass:[TextEditorViewController class]]){
        [vc setDelegate:self];
        [vc setDefaultText:[self.user valueForKey:propertyName]];
        [vc setTag:indexPath.row];
        BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
    if([vc isKindOfClass:[MobileBindViewController class]]){
        [vc setDelegate:self];
        [vc setMobile:[self.user valueForKey:propertyName]];
        BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        return;
    }
}
- (void)reloadTableViewForProperty:(NSString *)propertyName{
    for (NSInteger i = 0, n = self.editableFields.count; i < n; i++) {
        NSDictionary *conf = [self.editableFields objectAtIndex:i];
        if ([propertyName isEqualToString:conf[@"propertyName"]]) {
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            return;
        }
    }
}
#pragma mark - request
- (void)updateProfileForKey:(NSString *)key value:(id)val callback:(nullable void (^)(NSError * error))callback{
    
    //如果是批量更新
    if (!self.editPropertySingly) {
        [self.updatedUserInfo setValue:val forKey:key];
        return;
    }
    
    User *updatedUser = [User new];
    [updatedUser setValue:val forKey:key];
    
    [BKIndicator showTips:NSLocalizedString(@"submitting", @"提交数据") duration:0 completion:nil];
    [User update:updatedUser callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if(error){
            [BKIndicator showTips:error.localizedDescription duration:0.5 completion:nil];
            return;
        }
        if (!error) {
            [BKIndicator showTips:NSLocalizedString(@"update_success", @"提示") duration:0.5 completion:nil];
            [self.user setValue:val forKey:key];
            [User updateLoginUserInfo:self.user];
            [self reloadTableViewForProperty:key];
        }
        if (callback) {
            callback(error);
        }
    }];
}
- (void)updateUserName:(NSString *)userName callback:(nullable void (^)(NSError * error))callback{
    [BKIndicator showTips:NSLocalizedString(@"setting_userName_now", @"提交数据") duration:0 completion:nil];
    [User updateUserName:userName callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if(error){
            [BKIndicator showTips:error.localizedDescription duration:0.5 completion:nil];
            return;
        }
        if(!error){
            [BKIndicator showTips:NSLocalizedString(@"setting_success", @"提示") duration:0.5 completion:nil];
            [User updateLoginUserInfo:self.user];
        }
        if (callback) {
            callback(error);
        }
    }];
}
#pragma mark - TextEditorDelegate
- (void)textEditorViewControllerDidCanceledEdit:(TextEditorViewController *)vc{
    [vc dismissViewControllerAnimated:YES completion:nil];
}
- (void)textEditorViewControllerDidFinishedEdit:(TextEditorViewController *)vc{
    NSString *newVal = vc.textView.text;
    
    NSDictionary *field = [self.editableFields objectAtIndex:vc.tag];
    NSString *propertyName = [field valueForKey:@"propertyName"];
    NSString *oriVal = [self.user valueForKey:propertyName];
    //改变值了
    if (![newVal isEqualToString:oriVal]) {
        if ([propertyName isEqualToString:@"userName"]) {
            [self updateUserName:newVal callback:^(NSError *error) {
                if (!error) {
                    [vc dismissViewControllerAnimated:YES completion:nil];
                }
            }];
            return;
        }
        
        [self updateProfileForKey:propertyName value:newVal  callback:^(NSError *error) {
            if (!error) {
                [vc dismissViewControllerAnimated:YES completion:nil];
            }
        }];
        return;
    }
    [self.updatedUserInfo removeObjectForKey:propertyName];
    [vc dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - SelectionDelegate
- (void)selectionViewControllerDidCanceled:(SelectionViewController *)vc{
    [vc dismissViewControllerAnimated:YES completion:nil];
}
- (void)selectionViewController:(SelectionViewController *)vc didSelectItem:(SelectionItem *)item{
    NSDictionary *conf = [self.editableFields objectAtIndex:vc.tag];
    NSString *propertyName = conf[@"propertyName"];
    
    if ([@"gender" isEqualToString:propertyName]) {
        SysDictItem *dictItem = item.value;
        int newVal = [dictItem.value intValue];
        if (newVal != self.user.gender) {            
            [self updateProfileForKey:propertyName value:@(newVal) callback:^(NSError *error) {
                if (!error) {
                    [vc dismissViewControllerAnimated:YES completion:nil];
                }
            }];
            return;
        }
        [self.updatedUserInfo removeObjectForKey:propertyName];
    }
    [vc dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - MobileBindDelegate
- (void)mobileBindViewController:(MobileBindViewController *)vc didBindWithMobile:(NSString *)mobile{
    self.user.mobile = mobile;
    [User updateLoginUserInfo:self.user];
    [self.tableView reloadData];
}
- (void)mobileBindViewControllerDidCancel:(MobileBindViewController *)vc{
    
}
#pragma mark - action
- (IBAction)changeAvatar:(id)sender{
    BKActionSheet *actionSheet = [[BKActionSheet  alloc] initWithTitle:NSLocalizedString(@"change_avatar", @"按钮")
                                                                 items:@[@{
                                                                     @"title":NSLocalizedString(@"photo", @"按钮"),
                                                                     @"subtitle":NSLocalizedString(@"select_from_photo_lib", @"按钮"),
                                                                     @"tag":@ACTION_SHEET_ITEM_TAG_AVATAR_PHOTO_LIB
                                                                     },
                                                                 @{
                                                                     @"title":NSLocalizedString(@"take_photo", @"按钮"),
                                                                     @"tag":@ACTION_SHEET_ITEM_TAG_AVATAR_TAKE_PHOTO
                                                                     }]
                                                              delegate:self
                                                     cancelButtonTitle:NSLocalizedString(@"cancel", @"按钮")
                                                destructiveButtonTitle:nil];
    [actionSheet show];
}
- (void)actionSheet:(BKActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex data:(id)data{
    DLOG(@"actionSheet:%ld,%@", buttonIndex, data);
    WEAK(weakSelf, self);
    NSInteger tag = [[data valueForKey:@"tag"] intValue];
    switch (tag) {
        case ACTION_SHEET_ITEM_TAG_AVATAR_PHOTO_LIB:{
            PhotoLibViewController *vc = [[PhotoLibViewController alloc] init];
            vc.delegate = weakSelf;
            BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
            nav.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:nav animated:YES completion:^{
                
            }];
            break;
        }
        case ACTION_SHEET_ITEM_TAG_AVATAR_TAKE_PHOTO:{
            PhotoCameraViewController *imagePicker = [PhotoCameraViewController imagePickerControllerForTakePicture];
            imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
            imagePicker.photoEditDelegate = self;
            imagePicker.edit = YES;
            [self presentViewController:imagePicker animated:YES completion:^{
                
            }];
            break;
        }
        default:
            break;
    }
}
- (void)photoEditViewController:(id)controller didEditPhotos:(NSArray *)photos{
    if (!photos || photos.count == 0) {
        return;
    }
    
    PhotoAsset *photoAsset = photos.firstObject;
    self.avatarAsset = photoAsset;
    AvatarTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell.avatarButton setImageForState:UIControlStateNormal withURL:[NSURL fileURLWithPath:photoAsset.originPath]];
    
    [BKIndicator showTips:NSLocalizedString(@"uploading", @"提交数据")
                   inView:self.view
                 duration:0
               completion:nil];
    [User updateAvatar:photoAsset
    photoUploadProgress:^(NSString * _Nonnull key, float p) {
         
     }
               callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
         if (error) {
             [BKIndicator showTips:error.localizedDescription
                            inView:self.view
                          duration:0.1
                        completion:nil];
             return;
         }
         [BKIndicator showTips:NSLocalizedString(@"submit_success", @"提交数据")
                        inView:self.view
                      duration:1.0f
                    completion:nil];
     }];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
